package com.mini.mybatis.mybatisministep08.builder.xml;

import com.mini.mybatis.mybatisministep08.builder.BaseBuilder;
import com.mini.mybatis.mybatisministep08.mapping.MappedStatement;
import com.mini.mybatis.mybatisministep08.mapping.SqlCommandType;
import com.mini.mybatis.mybatisministep08.mapping.SqlSource;
import com.mini.mybatis.mybatisministep08.scripting.LanguageDriver;
import com.mini.mybatis.mybatisministep08.sqlsession.configuration.Configuration;
import org.dom4j.Element;

import java.util.Locale;

/**
 * 语句构造器
 */
public class XmlStatementBuilder extends BaseBuilder {

    private Element element;

    private String currentNamespace;


    public XmlStatementBuilder(Configuration configuration, Element element, String currentNamespace) {
        super(configuration);
        this.element = element;
        this.currentNamespace = currentNamespace;
    }

    // 这里是解析一个sql标签
    public void parse() {
        // id
        String id = element.attributeValue("id");
        // 参数类型
        String parameterType = element.attributeValue("parameterType");
        Class<?> parameterTypeClass = resolveAlias(parameterType);
        // 返回结果类型
        String resultType = element.attributeValue("resultType");
        Class<?> resultTypeClass = resolveAlias(resultType);
        // sql命令类型
        String name = element.getName();
        SqlCommandType sqlCommandType = SqlCommandType.valueOf(name.toUpperCase(Locale.ENGLISH));

        // 获取语言驱动器 这里暂时获取的是默认的xmlLanguageDriver,后续可通过配置获取对应类型的driver
        Class<?> langClass = configuration.getLanguageRegistry().getDefaultDriverClass();
        LanguageDriver langDriver = configuration.getLanguageRegistry().getDriver(langClass);
        // 通过语言驱动器来解析sql并封装为sqlSource，这里可以根据类型解析动态sql和静态sql
        SqlSource sqlSource = langDriver.createSqlSource(configuration, element, parameterTypeClass);
        MappedStatement mappedStatement = new MappedStatement.Builder(configuration, currentNamespace + "." + id, sqlCommandType, sqlSource, resultTypeClass).build();

        // 添加解析 SQL
        configuration.addMappedStatement(mappedStatement);
    }

}
